package com.company.controller;

import com.company.service.MsmService;
import com.company.servicebase.exception.MyException;
import com.company.utils.R;
import com.company.utils.RandomUtil;
import com.company.utils.RedisUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {

    @Resource
    private MsmService msmService;

    @Resource
    private RedisUtil redisUtil;

    //根据手机号码发送短信验证码
    @GetMapping("/send/{phone}")
    public R sendMsm(@PathVariable("phone") String phone) {

        String code = (String) redisUtil.get("phone");
        if (!StringUtils.isEmpty(code)){
            return R.ok();
        }

        code = RandomUtil.getFourBitRandom();
        Map<String, Object> map = new HashMap<>(1);
        map.put("code", code);
        boolean isSend = msmService.send(map, phone);

        if (isSend == true) {
            redisUtil.set(phone, code,300);
        } else {
            throw new MyException(20001, "短信发送失败");
        }
        return R.ok();
    }

}
